import math
# 节点类


class Node(object):
    def __init__(self, data=0):
        '''
        :param data: 节点数据
        '''

        self.data = data
        self.pre = None
        self.next = None

# 链表类


class List(object):
    def __init__(self):
        self.head = Node()
        self.tail = Node()
        self.head.next = self.tail
        self.tail.pre = self.head
        self.length = 0

        n = math.ceil(2.1)

    # 添加节点

    def insert(self, index, data):
        assert 0 <= index <= self.length
        node = Node(data)
        curNode = self.head
        while index:
            curNode = curNode.next
            index -= 1

        nNode = curNode.next

        curNode.next = node
        node.pre = curNode

        nNode.pre = node
        node.next = nNode

        self.length += 1

    #     在末尾添加

    def append(self, data):
        self.insert(self.length, data)

    #     输出指定位置

    def printIndex(self, index):
        assert 0 <= index < self.length
        node = self.head.next
        while index:
            node = node.next
            index -= 1
        print(node.data)

    #     遍历

    def foreach(self):
        first = self.head.next
        i = 0
        while i < self.length:
            yield first.data
            first = first.next
            i += 1

    # 通过下标删除

    def remove(self, index):
        assert 0 <= index < self.length
        # node = self.head
        # while index > 0:
        #     node = node.next
        #     index -= 1
        # # print(node.data)
        # node.next = node.next.next
        # node.next.next.pre = node
        node = self.head.next
        while index > 0:
            node = node.next
            index -= 1
        # print(node.data)
        # pnode = node.pre
        # nnode = node.next
        #
        # pnode.next = nnode
        # nnode.pre = pnode
        self.length -= 1

        node.pre.next = node.next
        node.next.pre = node.pre

    # __getitem__使用下标获取值l[0]、l[1]

    def __getitem__(self, item):
        assert isinstance(item, int)
        self.printIndex(item)

    # __setitem__使用l[2] = 5，来设置值

    def __setitem__(self, key, value):
        assert isinstance(key, int)
        self.insert(key, value)

    # 将List类变为和系统自带的list一样可以遍历的属性

    def __iter__(self):
        return self.foreach()

    def __len__(self):
        return self.length


if __name__ == '__main__':
    l = List()
    l.append(5)
    l.append(6)
    l.append(7)
    for c in l:
        print(c)
    print('===============')
    l.remove(1)
    for c in l:
        print(c)
    # print(l.length)
    # l[2]
